<?php
/**
 * 订单批量导入导出功能
 *
 * @author Administrator
 *
 */
class CSVService {
	
	private $_tempName = 'Filedata'; //上传文件名
	private $_fileTypes = array ('csv' ); // File extensions
	private $_targetFolder = '/static/attached/csv'; // Relative to the root
	private $_num = 40;
	private $_searchNum=500;
	private $_mubiao = array ('中原军区' => 1600, '西北军区' => 2100, '华东军区' => 2000, '华南军区' => 2250, '北方军区' => 1600 );
	const SUCCESS = 'success';
	const ERROR = 'error';
	
	private $_status = array (0 => "等待审核", "1" => "通过", "-1" => "不通过", "2" => "已中奖" );
	
	public function getTopJsx() {
		return CSVModel::instance ()->topTen ();
	}
	
	public function getPrize($round) {
		$prize = require 'prize.php';
		$rs = CSVModel::instance ()->getPrize ( $round );
		
		foreach ( $rs as $k => $v ) {
			//$user [$v ['uid']] = $v;
			$user [$v ['uid']] ['jxs'] = $v ['jxs'];
			$user [$v ['uid']] ['junqu'] = $v ['junqu'];
			$user [$v ['uid']] ['area'] = $v ['area'];
			$user [$v ['uid']] ['list'] [$v ['prize']] = $v;
		}
		
		foreach ( $user as $k => $v ) {
			
			foreach ( $prize as $pk => $pv ) {
				
				if (empty ( $v ['list'] [$pk] )) {
					$user [$k] ['list'] [$pk] ['price'] = 0;
					$user [$k] ['list'] [$pk] ['prizenum'] = 0;
					continue;
				}
				$hz [$pk] ['num'] += $user [$k] ['list'] [$pk] ['prizenum'];
				
				if ($prize [$pk] ['type'] != 'money') {
					$hz [$pk] ['price'] += $user [$k] ['list'] [$pk] ['prizenum'] * $pv ['price'];
					
					$user [$k] ['list'] [$pk] ['price'] = $pv ['price'] * $user [$k] ['list'] [$pk] ['prizenum'];
				} else {
					$hz [$pk] ['price'] += $user [$k] ['list'] [$pk] ['tmoney'] * $pv ['price'];
					$user [$k] ['list'] [$pk] ['price'] = $user [$k] ['list'] [$pk] ['tmoney'] * $pv ['price'];
				}
				$num += $user [$k] ['list'] [$pk] ['prizenum'];
				$total += $user [$k] ['list'] [$pk] ['price'];
			}
			
			$user [$k] ['num'] = $num;
			$user [$k] ['total'] = $total;
			$total = 0;
			$num = 0;
			ksort ( $user [$k] ['list'] );
		}
		ksort ( $hz );
		foreach ( $hz as $v ) {
			$number += $v ['num'];
			$money += $v ['price'];
		}
		
		return array ('prize' => $prize, 'user' => $user, 'hz' => $hz, 'money' => $money, 'number' => $number );
	}
	/**
	 * 
	 * 导入数据
	 * @param String $timestamp
	 * @param String $token
	 * @param array $user
	 */
	public function import($timestamp, $token, $user) {
		/*
		if (! $this->checkValidate ( $_POST ['codeimg'] )) {
			return "验证码错误";
		}
		*/
		
		$filename = $this->upload ();
		if ($filename == "error") {
			return "文件名不正确，应该是CSV文件，而不是xls文件";
		}
		$filename = getcwd () . $filename;
		
		if (! file_exists ( $filename )) {
			return "上传成功，但文件无法读取";
		}
		
		$rs = $this->parseCSV ( $filename, $user );
		unlink ( $filename );
		return $rs;
	}
	
	public function getOrderStat() {
		$pass = $this->getPassNum ();
		$reward = $this->getRewardNum ();
		return array ('pass' => $pass + $reward, 'reward' => $reward );
	}
	
	private function getPassNum() {
		return CSVModel::instance ()->countNum ( array ('status' => 1 ) );
	}
	
	private function getRewardNum() {
		return CSVModel::instance ()->countNum ( array ('status' => 2 ) );
	
	}
	
	//获取自己的订单信息
	public function getCSVByUid($uid) {
		$rs = CSVModel::instance ()->getCSV ( array ('uid' => $uid ) );
		foreach ( $rs as $k => $v ) {
			$rs [$k] ['status'] = $this->_status [$v ['status']];
		}
		return $rs;
	}
	
	public function listing($pageid) {
		$total = CSVModel::instance ()->countNum ( null );
		$page = $this->page ( $total, $pageid, $this->_num );
		$page ['total'] = $total;
		$rs = CSVModel::instance ()->listing ( $page ['start'], $this->_num, null );
		return array ('rs' => $rs, 'page' => $page );
	}
	
	public function stat() {
		//全部订单
		$rs = CSVModel::instance ()->stat ( null );
		//审核通过的盯电脑
		$legal = CSVModel::instance ()->stat ( 1 );
		
		foreach ( $rs as $k => $v ) {
			$arr [$k] = $v;
			$arr [$k] ['legal'] = $legal [$k] ['num'];
			$arr [$k] ['mubiao'] = $this->_mubiao [$v ['junqu']];
		}
		return $arr;
	
	}
	//区域经理订单状态
	public function manStatus() {
		//全部
		$rs = CSVModel::instance ()->statByMan ( null );
		//审核通过的
		$legal = CSVModel::instance ()->statByMan ( 1 );
		foreach ( $rs as $k => $v ) {
			$rs [$k] ['legal'] = $legal [$k] ['num'];
		}
		return $rs;
	
	}
	
	public function remove($id) {
		return CSVModel::instance ()->remove ( array ('id' => $id ) );
	}
	
	public function search($key, $value) {
		$where = array ($key => urldecode ( $value ) );
		$total = CSVModel::instance ()->countNum ( $where );
		$page = $this->page ( $total, 1, $total );
		$page ['total'] = $total;
		
		$rs = CSVModel::instance ()->listing ( $page ['start'], $this->_searchNum, $where );
		
		$pass = 0;
		$reward = 0;
		foreach ( $rs as $k => $v ) {
			
			if ($v ['status'] > 0) {
				$pass ++;
				$money += $v ['money'];
			
			}
			
			if ($v ['status'] == 2) {
				$reward ++;
			}
		
		}
		return array ('rs' => $rs, 'page' => $page, 'stat' => array ('pass' => $pass, 'reward' => $reward ), 'money' => $money );
	}
	
	/**
	 * 分页
	 *
	 * @return Array
	 */
	private function page($total, $pageid, $num) {
		$pageid = isset ( $pageid ) ? $pageid : 1;
		$start = ($pageid - 1) * $num;
		$pagenum = ceil ( $total / $num );
		/*修正分类不包含内容 显示404错误*/
		$pagenum = $pagenum == 0 ? 1 : $pagenum;
		/*如果超过了分类页数 404错误*/
		
		if ($pageid > $pagenum) {
			return false;
		}
		
		$page = array ('start' => $start, 'num' => $num, 'current' => $pageid, 'page' => $pagenum );
		return $page;
	}
	/**
	 * 检测验证码是否正确
	 */
	private function checkValidate($codeimg) {
		if (! isset ( $codeimg )) {
			return false;
		}
		if (trim ( $codeimg ) != $_SESSION ["authnum_session"]) {
			return false;
		}
		return true;
	}
	
	public function upload() {
		
		if (is_uploaded_file ( $_FILES [$this->_tempName] ['tmp_name'] )) {
			$upfile = $_FILES [$this->_tempName];
			$name = $upfile [name];
			$type = $upfile [type];
			$size = $upfile [size];
			$tmp_name = $upfile [tmp_name];
			$error = $upfile [error];
			//判断文件类型
			$fileType = 'csv';
			if (! $this->checkFileType ( $name )) {
				return "error";
			}
			
			$newName = time () . "." . $fileType;
			$filepath = "/static/attached/csv";
			
			$filepath = $filepath . DIRECTORY_SEPARATOR . $newName;
			move_uploaded_file ( $tmp_name, getcwd () . $filepath );
			
			return $filepath;
		}
	}
	//判断是否是csv类型的文件  可能不是正常的csv 
	private function checkFileType($fileName) {
		
		return preg_match ( "#\.csv+$#iUs", $fileName );
	}
	
	/**
	 * 解析CSV文件   
	 * 注意文件处理的大小
	 */
	public function parseCSV($filename, $user) {
		
		$handle = fopen ( $filename, 'r' );
		$result = $this->input_csv ( $handle ); //解析csv 
		$len_result = count ( $result );
		if ($len_result == 0) {
			return '没有任何数据！';
		}
		
		$notMatchFile = "";
		$line = "";
		$time = time ();
		//第一行去掉    军区 区域  业务经理 客户名称 客户手机 定金金额  客户地址
		//修正号码为空跳过   修正经销商为空 过滤掉
		$j = 0;
		$repeatnum = 0;
		for($i = 1; $i < $len_result; $i ++) {
			
			if (strlen ( $result [$i] [4] ) < 8) {
				continue;
			}
			//定位到第几行
			$line = $i + 1;
			$line = "第" . $line . "行出错,";
			
			$param ['junqu'] = iconv ( 'GB18030', 'utf-8', $result [$i] [0] ); //中文转码 
			

			if (! $this->matchJunQu ( $param ['junqu'] )) {
				return $line . "军区不正确，请填写完整，如华南军区，而不是华南";
			}
			
			$param ['area'] = iconv ( 'GB18030', 'utf-8', $result [$i] [1] ); //中文转码 
			

			if (empty ( $param ['area'] )) {
				return $line . "城市区域没有填写，请填写完整";
			}
			
			$param ['man'] = iconv ( 'GB18030', 'utf-8', $result [$i] [2] ); //中文转码 
			

			if (empty ( $param ['man'] )) {
				return $line . "业务经理没有填写，请填写完整";
			}
			
			if (! $this->matchMan ( $param ['man'] )) {
				return $line . "填写正确的业务经理名字";
			}
			
			$param ['customer'] = iconv ( 'GB18030', 'utf-8', $result [$i] [3] ); //中文转码 
			

			if (empty ( $param ['customer'] )) {
				return $line . "业主姓名没有填写，请填写完整";
			}
			
			$param ['mobile_phone'] = $result [$i] [4]; //中文转码 
			//号码重复跳过
			if (! $this->checkMobileIsRepeat ( $param ['mobile_phone'] )) {
				$repeatnum ++;
				unset ( $param );
				continue;
			}
			
			if (strlen ( $param ['mobile_phone'] ) != 11) {
				return $line . "手机不存在或者手机号码位数不对";
			}
			
			if ($this->isMobilePhoneLegal ( $param ['mobile_phone'] )) {
				
				return $line . "手机号码" . $param ['mobile_phone'] . "含有符号.或者英文字符E等，请检查更正";
			}
			
			$param ['money'] = $result [$i] [5]; //中文转码 
			

			if (round ( $param ['money'] ) < 1000 || round ( $param ['money'] ) > 5000) {
				return $line . "定金金额不能为空或小于1000或大于5000";
			}
			
			$param ['address'] = iconv ( 'GB18030', 'UTF-8', $result [$i] [6] ); //中文转码 
			

			if (empty ( $param ['address'] )) {
				return $line . "业主地址不能为空,错误信息" . $param ['address'];
			}
			
			$param ['add_time'] = $time;
			
			$param ['uid'] = $user ['uid'];
			$param ['jxs'] = $user ['real_name'];
			$this->addData ( $param );
			$j ++;
		}
		
		fclose ( $handle ); //关闭指针 
		

		$notice = '提交失败,数据未能读取或重复上传，重复数' . $repeatnum . '单';
		
		return $j > 0 ? $j : $notice;
	
	}
	
	/**
	 * 检查手机号码是否合法 科学技术
	 * @return boolean true 非法 false 合法
	 */
	private function isMobilePhoneLegal($mobile) {
		return preg_match ( "#[a-zA-Z|\.\+]+#iUs", $mobile );
	}
	
	//匹配是否填写了军区
	private function matchJunQu($jq) {
		$junqu = array ('北方军区', '华南军区', '西北军区', '华东军区', '中原军区' );
		return in_array ( $jq, $junqu );
	}
	
	//匹配区域经理真实姓名
	private function matchMan($manName) {
		$man = MemberModel::instance ()->getMemberByWhere ( array ('groupid' => 14, 'verify' => 1 ), 'real_name', null, 200 );
		
		if (empty ( $man )) {
			return false;
		}
		
		foreach ( $man as $v ) {
			if ($manName == $v ['real_name']) {
				return true;
			}
		}
		return false;
	}
	
	public function getAddLog() {
		$rs = CSVModel::instance ()->dateLog ( 7 );
		$num = count ( $rs )-1;
		foreach ( $rs as $k => $v ) {
			
			$arr [$k] = $rs [$num-$k];
			$arr [$k] ['add_time'] = date ( "n月j日", $rs [$num-$k]['add_time'] );
		}
		return $arr;
	}
	
	public function getMoney() {
		return CSVModel::instance ()->getMoney ();
	}
	
	/**
	 * 检查号码是否重复
	 * @param int $modile
	 * @return boolean 号码是否 重复false 不重复true
	 */
	private function checkMobileIsRepeat($modile) {
		$rs = CSVModel::instance ()->getCSV ( array ('mobile_phone' => $modile ) );
		return empty ( $rs );
	}
	/**
	 * 过滤
	 * Enter description here ...
	 */
	private function filter($line) {
	
	}
	
	private function addData($param) {
		
		CSVModel::instance ()->addOrder ( $param );
	}
	
	private function input_csv($handle) {
		$out = array ();
		$n = 0;
		while ( $data = fgetcsv ( $handle, 10000 ) ) {
			$num = count ( $data );
			for($i = 0; $i < $num; $i ++) {
				$out [$n] [$i] = $data [$i];
			}
			$n ++;
		}
		return $out;
	}
	private function setCsvHeader() {
		header ( "Cache-Control: public" );
		header ( "Pragma: public" );
		header ( "Content-type:application/vnd.ms-excel" );
		$file = date ( "md", time () );
		header ( "Content-Disposition:attachment;filename=$file.csv" );
	}
	/**
	 * 统计
	 */
	public function stats($uid) {
		
		$total = CSVModel::instance ()->countNum ( array ('uid' => $uid ) );
		$pass1 = CSVModel::instance ()->countNum ( array ('uid' => $uid, 'status' => 1 ) );
		$pass2 = CSVModel::instance ()->countNum ( array ('uid' => $uid, 'status' => 2 ) );
		$pass = $pass1 + $pass2;
		$rs = CSVModel::instance ()->top ();
		
		//如果为空的情况下
		if ($total > 0) {
			foreach ( $rs as $k => $v ) {
				if ($v ['uid'] == $uid) {
					$rank = $k;
					break;
				}
			}
		} else {
			$rank = count ( $rs );
		}
		
		return array ('total' => $total, 'pass' => $pass, 'rank' => $rank + 1 );
	
	}
	/**
	 * 导出
	 * Enter description here ...
	 */
	public function export($uid) {
		$this->setCsvHeader ();
		$rs = CSVModel::instance ()->getCSV ( array ('uid' => $uid ) );
		$title = "时间,军区,城市区域,业务经理,业主姓名,业主手机,定金金额,审核状态\n";
		echo $this->utf8ToGBK ( $title );
		$format = "%s,%s,%s,%s,%s,%s,%s,%s\n";
		foreach ( $rs as $v ) {
			
			echo sprintf ( $format, date ( "m/d", $v ['add_time'] ), $this->utf8ToGBK ( $v ['junqu'] ), $this->utf8ToGBK ( $v ['area'] ), $this->utf8ToGBK ( $v ['man'] ), $this->utf8ToGBK ( $v ['customer'] ), $v ['mobile_phone'], $v ['money'], $this->utf8ToGBK ( $this->_status [$v ['status']] ) );
		}
	
	}
	
	public function exportAll($id, $type) {
		$this->setCsvHeader ();
		$rs = $this->getExportType ( $id, $type );
		$title = "订单编号,时间,经销商,军区,城市区域,业务经理,业主姓名,业主手机,定金金额,审核状态\n";
		echo $this->utf8ToGBK ( $title );
		$format = "%s,%s,%s,%s,%s,%s,%s,%s,%s,%s\n";
		foreach ( $rs as $v ) {
			
			echo sprintf ( $format, $v ['id'], date ( "m/d", $v ['add_time'] ), $this->utf8ToGBK ( $v ['jxs'] ), $this->utf8ToGBK ( $v ['junqu'] ), $this->utf8ToGBK ( $v ['area'] ), $this->utf8ToGBK ( $v ['man'] ), $this->utf8ToGBK ( $v ['customer'] ), $v ['mobile_phone'], $v ['money'], $v ['status'] );
		
		}
	}
	//1 全部 2等待审核 3审核通过 4中奖的
	private function getExportType($id, $type) {
		
		switch ($type) {
			case 1 :
				$rs = CSVModel::instance ()->getCSVGreaterThanId ( $id, "all" );
				break;
			case 2 :
				$rs = CSVModel::instance ()->getCSVGreaterThanId ( $id, 0 );
				break;
			case 3 :
				$rs = CSVModel::instance ()->getCSVGreaterThanId ( $id, 1 );
				break;
			case 4 :
				$rs = CSVModel::instance ()->getCSVGreaterThanId ( $id, 2 );
				break;
		}
		return $rs;
	}
	
	//确认订单
	public function confirm() {
		
		$filename = $_FILES ['file'] ['tmp_name'];
		if (empty ( $filename )) {
			return '请选择要导入的CSV文件！';
		}
		
		$handle = fopen ( $filename, 'r' );
		$result = $this->input_csv ( $handle ); //解析csv 
		$len_result = count ( $result );
		if (! $len_result) {
			return '没有任何数据！';
		}
		$notMatchFile = "";
		$line = "";
		$this->setCsvHeader ();
		
		for($i = 0; $i < $len_result; $i ++) { //循环获取各字段值 
			

			$rs = CSVModel::instance ()->saveCSVStatus ( array ('status' => $result [$i] [1], 'prize' => $result [$i] [2], 'round' => $result [$i] [3] ), array ('id' => $result [$i] [0] ) );
			//可能存在没有更新的情况
			if ($rs < 1) {
				echo $result [$i] [0] . "\n";
			}
		
		}
		fclose ( $handle ); //关闭指针 
		return;
	}
	private function utf8ToGBK($value) {
		return iconv ( 'UTF-8', 'GB18030', $value );
	}

}